/*
	任务量未达成数据
*/
public without sharing class UnqualifiedDeliveController {
    
	public String msg {get;private set;}
	public Boolean isSuccess {get; private set;}
	public String resJson {get; private set;}
	public String saveJson {get;  set;}

    public UnqualifiedDeliveController() {
        
    }

    public void setNil(){

    	resJson = '[]';
    	saveJson = '[]';

    }

    private String getQuater(Decimal q){
    	if(q == 1) return '一季度';
    	if(q == 2) return '二季度';
    	if(q == 3) return '三季度';
    	if(q == 4) return '四季度';
    	return null;

    }

    public void dispatch(){
    	msg = '';
    	 Integer y = System.now().year();
		 Integer q = Integer.valueOf((System.now().month()-1) / 3 );
		 if(q == 0){
		 	q = 4;
		 	y -=1 ;
		 }
    	String year = String.valueOf(y)+'年';
    	String quarter = getQuater(q) ;
    	if( [select count() from ApplicationForUnqualifiedDelive__c where Year__c =: year and Quarter__c=: quarter ]>0){
    		msg = '本季度已分配给销售,请不要重复分配!';
    		//return;
		}
    	
    	List<Object> saveList = (List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
    	Map<Id ,List<ApplicationForUnqualifiedDeliveDetail__c>> adMap  = new Map<Id,List<ApplicationForUnqualifiedDeliveDetail__c>> ();
    	List<ApplicationForUnqualifiedDelive__c> afdList = new List<ApplicationForUnqualifiedDelive__c>();
    	
    	Set<String>proLines = new Set<String>();
        Set<String> accpks = new  Set<String>();
    	for(Object o :saveList ){
    		Map<String,Object> mo  = (Map<String,Object>)o;

    		ApplicationForUnqualifiedDeliveDetail__c ad = new ApplicationForUnqualifiedDeliveDetail__c();
    		ad.ProductLine__c = String.valueOf(mo.get('productline'));
    		proLines.add(ad.ProductLine__c);
    		ad.TaskMargin__c = DataUtil.getDecimalValue(mo.get('unfinishtask'));
    		ad.QuarterlyTaskVolume__c  = DataUtil.getDecimalValue(mo.get('currenttask'));
    		Id  accId = Id.valueOf(DataUtil.getStringValue(mo.get('accId')));

    		List<ApplicationForUnqualifiedDeliveDetail__c> tmp = adMap.containsKey(accId) ? adMap.get(accId) : new  List<ApplicationForUnqualifiedDeliveDetail__c> ();
    		if(!adMap.containsKey(accId))afdList.add(new ApplicationForUnqualifiedDelive__c(Account__c=accId ,Year__c=year,Quarter__c=quarter,OwnerId = DataUtil.getStringValue(mo.get('accOwnerId')) ));
    		tmp.add(ad);

    		adMap.put(accId , tmp);
            if(mo.get('ncicode') != null )accpks.add(DataUtil.getStringValue(mo.get('ncicode')));


    	}
    	//存在的明细
    	/*Map<String,Id >  adexistMap = new Map<String,Id >();
    	for(ApplicationForUnqualifiedDeliveDetail__c adf : [select Id ,  ProductLine__c,ApplicationForUnqualifiedDelive__r.Account__c ,ApplicationForUnqualifiedDelive__r.Year__c , ApplicationForUnqualifiedDelive__r.Quarter__c 
    	 	from ApplicationForUnqualifiedDeliveDetail__c where 
    	  	ProductLine__c in:proLines and ApplicationForUnqualifiedDelive__r.Account__c in:adMap.keySet() 
    	  	and ApplicationForUnqualifiedDelive__r.Year__c =:year and ApplicationForUnqualifiedDelive__r.Quarter__c =:quarter ]){

    		adexistMap.put(afd.ProductLine__c+afd.ApplicationForUnqualifiedDelive__r.Account__c , afd.Id  );
    	}
    	//存在的
    	*/

    	SavePoint sp = Database.setSavepoint();
    	try {

    		delete [select Id from ApplicationForUnqualifiedDeliveDetail__c where ApplicationForUnqualifiedDelive__r.Year__c =: year and ApplicationForUnqualifiedDelive__r.Quarter__c=:quarter ];
    		
    		delete [select Id from ApplicationForUnqualifiedDelive__c where Year__c =: year and Quarter__c=: quarter ];

    	    List<ApplicationForUnqualifiedDeliveDetail__c> adList = new List<ApplicationForUnqualifiedDeliveDetail__c>();
    	    if(afdList.size() > 0 ) insert afdList;
    	    for(ApplicationForUnqualifiedDelive__c afd : afdList){
    	    	List<ApplicationForUnqualifiedDeliveDetail__c> tmp = adMap.get(afd.Account__c);
    	    	if(tmp != null  && tmp.size() > 0){
    	    		for (ApplicationForUnqualifiedDeliveDetail__c ad  : tmp) {
    	    			ad.ApplicationForUnqualifiedDelive__c = afd.Id;
    	    			//ad.Id  = adexistMap.get(ad.ProductLine__c + afd.Account__c);
    	    			adList.add(ad);
    	    		}
    	    		
    	    	}
    	    }
    	    adMap.clear();
    	    if(afdList.size() > 0 ) upsert  adList;
    	   

            UnqualifiedDeliveController.sync(accpks,'NCTEST' );

             isSuccess = true;
            msg = '保存成功!';

    	}
    	catch (Exception e) {
    	    msg = '保存失败!'+e.getMessage();
    	    Database.rollback(sp);
    	}
    	

    }

    // @Future
    // public static void sync1(Set<String> accPks,String tag ){
    //     async(accPks,tag);

    // }
    ///回写 标记到NC客户档案
    @Future(callout=true)
    public static void sync(Set<String> accPks,String tag ){
       // async(accPks,tag);
    }
    
    public  static void  async(Set<String> gsbm ,  Set<String> accPks,String tag  ){

        String url = 'https://esb.maccura.com:9088/api/Domain/univer/dbbus/search';

        Map<String, String >dataMap = new Map<String,String>();
        dataMap.put('source','NCTEST');
        dataMap.put('tag',tag );
        dataMap.put('pk','\''+String.join(new List<String>(accPks),'\',\'')+'\'');
        dataMap.put('gsbm','\''+String.join(new List<String>(gsbm),'\',\'')+'\'');

        System.debug(JSON.serialize(dataMap));

        //请求
        HttpRequest req = new HttpRequest();
        req.setBody(JSON.serialize(dataMap) );
        req.setMethod('POST');
        req.setHeader('Content-Type','text/plain');
        req.setEndpoint(url);
        HttpResponse res = Utils.postRequest(req, 2);
        Boolean isSuc  = false;
        String sycmsg = '';
      ///返回结果处理
        if (res.getStatusCode() == 200) {
            System.debug(res.getBody());
            Map<String,Object> r = null;
              //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{\"result\":\"该SQL语句影响的记录有1条\",\"code\":\"0\",\"msg\":\"success\"}');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }
          if(r.get('code') == 0 || r.get('code') == '0'){
                Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
                System.debug(rs.get('result') != '该SQL语句影响的记录有0条');
              if( (rs.get('code') == 0 || rs.get('code') == '0' ) && rs.get('result') != '该SQL语句影响的记录有0条'){
                    isSuc = true;
               }else{
                    sycmsg = '同步客户未达成任务量标记失败 : '+rs.get('result');
               }

        }else{

            sycmsg = '同步客户未达成任务量标记失败 : '+String.valueOf(r.get('msg'));
        }

      }else{
            sycmsg = '同步客户未达成任务量标记失败 : '+res.getBody();
      }
      if(!isSuc){
          Task t = new Task();
          t.Subject = '同步客户未达成任务量标记失败';
          t.WhoId = [select Id from User where EmployeeNumber =:Label.FailureContact].Id ;
          t.Description = sycmsg + JSON.serialize(accpks);
          t.ActivityDate = System.today();
         
          insert t ; 

      }


    }   

    public  void  getDetails(){
    		 msg = '';

    		 Integer year = System.now().year();
    		 Integer quarter = Integer.valueOf((System.now().month()-1) / 3 +1 );
    		 

    	   	Map<String,String> data = new Map<String,String>();
            data.put('url','jdbc:oracle:thin:@192.168.30.34:1521:dw');
            data.put('username','dw');
            data.put('password','abc,.123');

            data.put('sql',getSql(year,quarter));


            Map<String,Object> paramsJson = new  Map<String,Object>() ;
            paramsJson.put('type','oracle');
            paramsJson.put('data',data);
            Blob key = Blob.valueOf('BCFD3E51207C0CF5');
			//Blob key =  Crypto.generateAesKey(128);
			// Crypto.generateAesKey(128);
		
			System.debug(EncodingUtil.base64Encode(key));

			Blob d = Blob.valueOf(JSON.serialize(paramsJson));
			String  encrypted = EncodingUtil.base64Encode(Crypto.encrypt('AES128', key, key, d));
			System.debug(encrypted);
            String url = 'https://esb.maccura.com:9088/api/Domain/univer/db/search?type=CBC&data='+encrypted;

			System.debug(url);
            HttpRequest req =  new HttpRequest();
            req.setEndpoint(url);
            req.setMethod('GET');
	        //设置提交超时时间(毫秒)
	        req.setTimeout(40000);
	        Http httpProtocol = new Http();
	        HttpResponse res = null;
	       
	        //连接超时标记	        
            try{
                if(Test.isRunningTest()){
                    res = new HttpResponse();
                    res.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=GB2312');
                    res.setBody('result=0&confirm_time=2017-01-23 10:15:26&id=2001063&replys=[{"callmdn":"10656584854","mdn":"13929512501","content":"B","reply_time":"2017-01-01 16:37:31","id":"2001062"},{"callmdn":"10656485545","mdn":"18122266563","content":"A","reply_time":"2017-01-01 10:15:26","id":"2001063"}]');
                    res.setStatusCode(200);
                }else{
                    res = httpProtocol.send(req);



                    System.debug(res.getBody());


                    if (res.getStatusCode() == 200) {
				            Map<String,Object> r = null;
				              //如果是测试
				                if(Test.isRunningTest()){
				                  Map<String,Object>  resBody= new Map<String,Object>();
				                  resBody.put('code','0');
				                  resBody.put('result','{"result":[{"CURRENTTASK":".2229","INVCLSFYJNAME":"病理","UNFINISHTASK":".0743","ACCOUNTID":"0010I00001bRY9cQAG"}],"code":"0","msg":"success"}');
				                    r =  resBody;
				                }else{
				                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
				                }
				          // r = (Map<String,Object>) JSON.deserializeUntyped(res.getBody());
				          if(r.get('code') == 0 || r.get('code') == '0'){
				             Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
				              if( rs.get('code') == '0'){
				                Set<String> accIdset  = new Set<String>();
				                  List<Object> datas = (List<Object>)rs.get('result');

				                  List<TaskBean> tbList = new List<TaskBean>();
				                  for(Object ob :datas){
				                    	Map<String,Object> m = (Map<String,Object>) ob;
				                    	TaskBean tb = new TaskBean(m);
				                    	accIdset.add(tb.accId);
				                    	tbList.add(tb);

				                  }

				                  Map<String,Account> accMap = new Map<String,Account>();
				                  for(Account acc : [select Id,Name , OwnerId , Owner.Name, NCICCode__c from Account where Id in: accIdset]){
				                  	  accMap.put(acc.Id , acc);
				                  }
				                   accIdset.clear();
				                 for(TaskBean tb : tbList){
				                  		if(accMap.containsKey(tb.accId)){
				                  			tb.accName = accMap.get(tb.accId).Name ;
				                  			tb.accOwnerId = accMap.get(tb.accId).OwnerId;
				                  			tb.saler = accMap.get(tb.accId).Owner.Name ;
                                            tb.ncicode = accMap.get(tb.accId).NCICCode__c ;
				                  		}
				                  }

				               
				                  resJson = EncodingUtil.urlEncode(JSON.serialize(tbList), 'UTF-8') ;

				               }else{
				                 msg = String.valueOf(rs.get('result_msg'));
				               }

				          //resJson = EncodingUtil.urlEncode(res.getBody(), 'UTF-8') ;
				        }else{
				          msg = '获取未达成任务量数据失败 : '+String.valueOf(r.get('msg'));
				           ///System.debug(res.toString());
				          //resJson = EncodingUtil.urlEncode('{"result":"","code":"1","msg":"接口错误,查询失败!"}','UTF-8');
				        }

				      }else{
				        msg = '获取未达成任务量数据失败 : '+res.getBody();
				      }
                }
            }catch(Exception ex){
            	msg = '获取未达成任务量数据失败 : '+ex.getMessage() + ex.getStackTraceString();
               //System.debug(ex.getMessage());
            }
		/*List<TaskBean> tbList = new List<TaskBean>();
		TaskBean t = new TaskBean();
		t.accName = 'xxx';
		t.currenttask = '10';
		t.productline = '生化';
		t.unfinishtask = '111';
		tbList.add(t);
            resJson = EncodingUtil.urlEncode(JSON.serialize(tbList), 'UTF-8') ;*/



    }

    /*
	* year 当前年
	* quarter 当前季度
    */
    private  String getSql( Integer year ,Integer quarter ){
    	//	'round(sum(case when year_=\'2019\' and (FLOOR((ltrim(MONTH_,\'0\')-1)/3)+ 1)< 3 then nvl(ASSIGNAMOUNT__C,0) else null end),4) 本年截止上季度任务量, '+
		//	'round(sum(case when year_=\'2019\' and (FLOOR((ltrim(MONTH_,\'0\')-1)/3)+ 1)< 3 then nvl(TASKNMNY,0) else null end),4) 本年截止上季度已完成, '+

    	Integer lyear = year;
    	Integer lquarter = quarter -1 ;

    	if(lquarter == 0){
    		lquarter = 4;
    		lyear -= 1;
    	}

    	return 	' select '+
			   	' nvl(b.ACCOUNTID,c.ACCOUNTID) ACCOUNTID, '+
				'INVCLSFYJNAME, '+
				'round(sum(case when year_=\''+lyear +'\' and (FLOOR((ltrim(MONTH_,\'0\')-1)/3)+ 1)<= '+lquarter+' then nvl(ASSIGNAMOUNT__C,0)-nvl(TASKNMNY,0) else null end),4) unfinishtask , '+
			
				'round(sum(case when year_=\''+year +'\' and (FLOOR((ltrim(MONTH_,\'0\')-1)/3)+ 1)='+quarter+' then nvl(ASSIGNAMOUNT__C,0) else null end),4)  currenttask  '+
				'from FACT_SALETASK_CHFL a  '+
				'left join stg_sf_account b on a.pk_cubasdoc=b.NCICCODE__C  '+
				'left join stg_sf_account c on a.ACCOUNTNAME__C=c.ACCOUNTNAME__C  '+
				'where nvl(b.ACCOUNTID,c.ACCOUNTID) is not null '+
			
				(lyear == year ? 'and YEAR_=\''+year +'\' ' : 'and YEAR_ in (\''+year+'\',\''+lyear+'\') ')+

				'and BRAND_XIN=\'迈克\'  '+
				//' and a.pk_cubasdoc = \'0001A0100000003HDI49\' '+

				'group by nvl(b.ACCOUNTID,c.ACCOUNTID),INVCLSFYJNAME '+
				'having sum(case when year_=\''+lyear +'\' and (FLOOR((ltrim(MONTH_,\'0\')-1)/3)+ 1) <='+lquarter+' then nvl(ASSIGNAMOUNT__C,0)-nvl(TASKNMNY,0) else null end) >0 ';
    }

    public class TaskBean{

    	public String productline;
    	public String accId ; 
    	public String unfinishtask; //UNFINISHTASK;
    	public String currenttask ;//CURRENTTASK;
    	public String accName;
    	public String saler ;
        public String ncicode; 

    	public String accOwnerId;
    	public TaskBean(){}
    	public TaskBean(Map<String,Object> mo ){
    		productline = String.valueOf(mo.get('INVCLSFYJNAME'));
    		accId = Id.valueOf(String.valueOf(mo.get('ACCOUNTID')));
    		unfinishtask = String.valueOf(mo.get('UNFINISHTASK'));
    		currenttask = String.valueOf(mo.get('CURRENTTASK'));
    	}
    }
}